package com.gg.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.gg.dao.ResourceDao;
import com.gg.entity.Resource;
import com.gg.util.MimeType;

public class ResourceServlet extends HttpServlet {
	@Autowired
	private ResourceDao resourceDao;

	@Override
	public void init() throws ServletException {
		this.resourceDao = new ResourceDao();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path = req.getRequestURI();
		Resource resource = this.resourceDao.getById(path);
		if (resource == null) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND,
					"File was not specified");
			return;
		}
		if (resource.getLastModifiedTime().equals(
				req.getHeader("If-Modified-Since"))) {
			resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		resp.setHeader("Content-type", MimeType.getContentTypeByExt(resource
				.getPath()));

		resp.setHeader("Content-Length", String.valueOf(resource.getContent()
				.getBytes().length));
		resp.setHeader("Last-Modified", resource.getLastModifiedTime());
		BufferedOutputStream output = new BufferedOutputStream(resp
				.getOutputStream());
		output.write(resource.getContent().getBytes());
		output.flush();
		output.close();
	}
}
